package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.bean.UserInfo;
import com.lily.aidouzixun.fragment.UserCenterFragment;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.ImageTextView;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.Map;


/**
 * 用户登录
 */
public class LoginActivity extends Activity {
    private static final String TAG = "LoginActivity";

    private TitleBar mTitleBar;
    private EditText etUsername;
    private EditText etPassword;
    private Button bnLogin; //登录按钮
    private TextView tvRegister;    //注册
    private TextView tvForgetPwd;   //忘记密码
    private TextView tvLoginType;  //登陆类型
    private Button bnVerification;  //得到验证码
    private static ProgressDialog mProgressDialog; //网络请求时用的进度条
    private ImageTextView itvQQLogin;

    private String key = "";
    private Activity mActivity;
    private static Context mContext;
    private String backTitle;   //返回标题
    private static final String TITLE = "登录";
    private MyHandler myHandler;

    private String username;    //用户名
    private String password;    //密码
    private int loginType = 1;  //登陆类型：1-密码登陆；2-手机号快捷登陆
    private static final int LOGIN_PASSWORD = 1;    //密码登陆
    private static final int LOGIN_PHONE = 2;       //手机号快捷登陆
    private String openId = ""; //QQ登录成功返回的Id,即QQ登录的唯一标示
    /**
     * 重新发送的时间
     */
    private static int resendTime = 30;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            init();
            findViews();
            setListeners();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化参数
     */
    private void init() {
        this.key += this.hashCode();
        mActivity = LoginActivity.this;
        mContext = LoginActivity.this;
        //得到返回标题
        Intent intent = getIntent();
        backTitle = intent.getStringExtra(MyConstant.IntentKey.BACK_TITLE);
        myHandler = new MyHandler(mActivity);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
    }

    /**
     * 找到控件
     */
    private void findViews() {
        //标题栏
        mTitleBar = (TitleBar) this.findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);
        //登录
        etUsername = (EditText) this.findViewById(R.id.et_username);
        etPassword = (EditText) this.findViewById(R.id.et_password);
        tvLoginType = (TextView) this.findViewById(R.id.tv_login_type);
        bnLogin = (Button) this.findViewById(R.id.bn_login);
        bnVerification = (Button) this.findViewById(R.id.bn_verification);
        //注册，忘记密码
        tvRegister = (TextView) this.findViewById(R.id.tv_register);
        tvForgetPwd = (TextView) this.findViewById(R.id.tv_forgetpwd);
        itvQQLogin = (ImageTextView) this.findViewById(R.id.itv_qqlogin);
    }

    /**
     * 设置监听
     */
    private void setListeners() {

        //切换登陆类型
        tvLoginType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (loginType) {
                    case LOGIN_PASSWORD:    //密码登陆
                        loginType = LOGIN_PHONE;
                        bnVerification.setVisibility(View.VISIBLE);
                        mTitleBar.setTitle("手机号快捷登陆");
                        tvLoginType.setText("密码登陆");
                        etUsername.setHint("请输入手机号");
                        etPassword.setHint("请输入验证码");
                        break;

                    case LOGIN_PHONE:  //手机号快捷登陆
                        loginType = LOGIN_PASSWORD;
                        bnVerification.setVisibility(View.GONE);
                        mTitleBar.setTitle("用户登录");
                        tvLoginType.setText("手机号快捷登陆");
                        etUsername.setHint("请输入用户名");
                        etPassword.setHint("请输入密码");
                        break;

                    default:
                        break;
                }
            }
        });
        //登录
        bnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                username = etUsername.getText().toString().trim();
                password = etPassword.getText().toString().trim();
                //用户登录
                userLogin(username, password);

            }
        });
        //跳转到用户注册页面
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, RegisterActivity.class);
                intent.putExtra(MyConstant.IntentKey.BACK_TITLE, TITLE);
                startActivityForResult(intent, 1);
            }
        });
    }

    /**
     * 处理注册
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            username = data.getExtras().getString(MyConstant.IntentKey.USER_NAME);
            password = data.getExtras().getString(MyConstant.IntentKey.PASSWORD);
            if (Validator.isEffective(username) && Validator.isEffective(password)) {
                etUsername.setText(username);
                etPassword.setText(password);
                userLogin(username, password);
            }
        }
    }

    /**
     * 用户登录
     */
    private void userLogin(String username, String password) {
        if (!Validator.isEffective(username)) {
            T.longToast(mContext, "用户名不能为空！");
            return;
        }
        if (!Validator.isEffective(password)) {
            T.longToast(mContext, "密码不能为空！");
            return;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.USER_NAME, username);
        param.put(MyConstant.RequireParams.PASSWORD, password);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key);
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.USER_LOGIN);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 登录成功
     */
    private void loginSuccess(UserInfo userinfo) {
        if (Validator.isEffective(userinfo.getUrid())) {  //设置用户id
            MyConfig.setUserId(mContext, userinfo.getUrid());
        }
        if (userinfo != null) {
            MyConfig.setUserInfo(mContext, userinfo);
        }
        //把用户信息传递到用户中心页面
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putParcelable("userinfo", userinfo);
        intent.putExtras(bundle);
        mActivity.setResult(MyConstant.IntentForResultCODE.LOGIN_RESULTCODE, intent);
        mActivity.finish();
        MessageDispatcher.sendMessage(UserCenterFragment.getMyHandler(), MessageType.LOGIN_STATUS_CHANGED);
    }

    /**
     * 用于短信登录成功以后，绑定手机号
     */
    private void bindSMS() {
        if (!Validator.isEffective(username)) {
            return;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.PHONE, username);
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.BIND_PHONE);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.BIND_PHONE);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 用于QQ登录成功以后，绑定账号
     *
     * @param userInfo
     */
    private void bindQQ(UserInfo userInfo) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.NICKNAME, userInfo.getNickname());
        param.put(MyConstant.RequireParams.AVATAR, userInfo.getAvatarUrl());
        param.put(MyConstant.RequireParams.QQ_ID, userInfo.getOpenId());
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.BIND_QQ);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.BIND_QQ);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //SMSSDK.unregisterAllEventHandler();
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         *
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final LoginActivity activity = (LoginActivity) mActivityReference.get();
                if (activity != null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (mProgressDialog != null) {
                                if (msg.arg1 == MyConstant.DataType.USER_LOGIN) {
                                    mProgressDialog.setMessage("正在登陆...");
                                    mProgressDialog.show();
                                } else if (msg.arg1 == MyConstant.DataType.BIND_QQ) {
                                    mProgressDialog.setMessage("正在QQ登陆...");
                                    mProgressDialog.show();
                                }
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == MyConstant.DataType.USER_LOGIN) {
                                SparseArray<Object> loginResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) loginResult.get(0);
                                if ("0".equals(errno)) {  //登陆成功
                                    UserInfo userInfo = (UserInfo) loginResult.get(2);
                                    if (userInfo != null) {
                                        T.shortToast(mContext, (String) loginResult.get(1));
                                        activity.loginSuccess(userInfo);    //登录成功的处理
                                    }
                                } else if ("1".equals(errno)) { //登陆失败
                                    T.shortToast(mContext, (String) loginResult.get(1));
                                }
                            } else if (msg.arg1 == MyConstant.DataType.BIND_QQ) {   //绑定QQ
                                SparseArray<Object> bindResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) bindResult.get(0);
                                if ("0".equals(errno)) {  //QQ登录成功
                                    UserInfo userInfo = (UserInfo) bindResult.get(2);
                                    if (userInfo != null) {
                                        activity.loginSuccess(userInfo);    //登录成功的处理
                                    }
                                } else if ("1".equals(errno)) { //登陆失败
                                    T.shortToast(mContext, (String) bindResult.get(1));
                                }
                            } else if (msg.arg1 == MyConstant.DataType.BIND_PHONE) {   //绑定手机号
                                SparseArray<Object> bindResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) bindResult.get(0);
                                if ("0".equals(errno)) {  //手机号登录成功
                                    UserInfo userInfo = (UserInfo) bindResult.get(2);
                                    if (userInfo != null) {
                                        activity.loginSuccess(userInfo);    //登录成功的处理
                                    }
                                } else if ("1".equals(errno)) { //登陆失败
                                    T.shortToast(mContext, (String) bindResult.get(1));
                                }
                            }
                            break;
                        case MessageType.UPDATE_DOWNTIME:   //更新倒计时
                            activity.bnVerification.setText("重新发送(" + resendTime + ")");
                            break;
                        case MessageType.RESEND:    //可以重新发送
                            resendTime = 30;
                            activity.bnVerification.setText("得到验证码");
                            activity.bnVerification.setClickable(true);
                            break;
                        case MessageType.QQ_LOGIN_SUCCESS:
                            JSONObject response = (JSONObject) msg.obj;
                            if (response != null) {
                                UserInfo userInfo = UserInfo.parseQQUser(response);
                                if (userInfo != null) {
                                    //这里要设置urid
                                    if (Validator.isEffective(activity.openId)) {
                                        userInfo.setOpenId(activity.openId);
                                    }
                                    // 绑定QQ号到服务器
                                    activity.bindQQ(userInfo);
                                }
                            }
                            break;
                        case MessageType.UMENG_QQ_LOGIN_SUCCESS:    //友盟QQ登录成功
                            Map<String, Object> umengQQResult = (Map<String, Object>) msg.obj;
                            if (umengQQResult != null) {
                                UserInfo userInfo = UserInfo.parseUmengQQUser(umengQQResult);
                                if (userInfo != null) {
                                    activity.bindQQ(userInfo);
                                }
                            }
                            break;

                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
}
